package com.example.blog.admin.service.impl;

import com.alibaba.fastjson.JSON;
import com.example.blog.dao.pojo.SysUser;
import com.example.blog.admin.service.TokenService;
import com.example.blog.utils.JWTUtils;
import com.example.blog.admin.vo.LoginUserVo;
import com.example.blog.admin.vo.ErrorCode;
import com.example.blog.admin.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Map;

@Service
public class TokenServiceImpl implements TokenService {
    
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result findUserByToken(String token) {
        /**
         * 1.验证token 是否合法
         * 2.若不合法，失败
         * 3.若合法，在redis中验证token是否过时
         * 4.未过时，返回redis中存储的用户数据
         */
//        if (StringUtils.isBlank(token)) {
//            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
//        }
        SysUser sysUser = this.checkLogin(token);

        if (sysUser == null) {
            return Result.fail(ErrorCode.TOKEN_ERROR.getCode(), ErrorCode.TOKEN_ERROR.getMsg());
        }

        LoginUserVo loginUserVo = new LoginUserVo();
        loginUserVo.setId(String.valueOf(sysUser.getId()));
        loginUserVo.setAccount(sysUser.getAccount());
        loginUserVo.setAvatar(sysUser.getAvatar());
        loginUserVo.setNickname(sysUser.getNickname());
        return Result.success(loginUserVo);
    }

    @Override
    public SysUser checkLogin(String token) {
        Map<String, Object> stringObjectMap = JWTUtils.checkToken(token);
        if (stringObjectMap == null) {
            return null;
        }
        String userJson = redisTemplate.opsForValue().get("TOKEN_" + token);
        if (userJson == null) {
            // token 过时
            return null;
        }
        SysUser sysUser = JSON.parseObject(userJson, SysUser.class);
        return sysUser;
    }


}
